package com.joolun.script.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joolun.script.entity.CommonConfig;
import com.joolun.script.enums.CommonConfigEnum;
import com.joolun.script.mapper.CommonConfigMapper;
import com.joolun.script.service.CommonConfigService;
import com.joolun.weixin.utils.GsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 通用配置
 *
 * @author zkk
 * @date 2022-01-12 15:55:36
 */
@Service
public class CommonConfigServiceImpl extends ServiceImpl<CommonConfigMapper, CommonConfig> implements CommonConfigService {

    private static final String SCRIPT = "script" ;
    private static final String EMAIL = "email" ;

    @Override
    public String queryByModuleAndKey(String module, String key) {
        CommonConfig commonConfig = getCommonConfig(module, key);
        if (Objects.nonNull(commonConfig)) {
            return commonConfig.getValue();
        }
        return null;
    }

    public CommonConfig getCommonConfig(String module, String key) {
        LambdaQueryWrapper<CommonConfig> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CommonConfig::getModule, module);
        queryWrapper.eq(CommonConfig::getKey, key);
        queryWrapper.last("limit 1");
        CommonConfig commonConfig = baseMapper.selectOne(queryWrapper);
        return commonConfig;
    }

    @Override
    public String saveV2(String appId, String value) {
        synchronized (this) {
            CommonConfig commonConfig = getCommonConfig(SCRIPT, EMAIL);
            if (Objects.nonNull(commonConfig)) {
                commonConfig.setValue(value);
                baseMapper.updateById(commonConfig);
            } else {
                baseMapper.insert(buildCommonConfig(appId, value));
            }
        }
        return value;
    }

    private CommonConfig buildCommonConfig(String appId, String value) {
        CommonConfig config = new CommonConfig();
        config.setAppId(appId);
        config.setCreateTime(LocalDateTime.now());
        config.setModule(SCRIPT);
        config.setKey(EMAIL);
        config.setValue(value);
        config.setRemark("邮箱");
        return config;
    }

    @Override
    public String queryEmail() {
        return queryByModuleAndKey(SCRIPT, EMAIL);
    }

    @Override
    public String queryByEnum(CommonConfigEnum configEnum) {
        return queryByModuleAndKey(configEnum.getModule(), configEnum.getKey());
    }

}
